package com.nytd.demo.common.util;

import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

public class SecurityUtil {
    public static String encrypt(String password) {
        String salt = UUID.randomUUID().toString().replace("-", "");
        String finalPassword = DigestUtils.md5DigestAsHex(
                (salt + password).getBytes(StandardCharsets.UTF_8));
        return salt + finalPassword;
    }

    public static boolean verify(String password, String finalPassword) {
        if (!StringUtils.hasLength(password) || !StringUtils.hasLength(finalPassword)) {
            return false;
        }
        if (finalPassword.length() != 64) {
            return false;
        }
        String salt = finalPassword.substring(0, 32);
        String securityPassword = DigestUtils.md5DigestAsHex(
                (salt + password).getBytes(StandardCharsets.UTF_8));
        return (salt + securityPassword).equals(finalPassword);
    }
}
